Ext.extend(avatar.module, {
	refresh : function(){
		var me = this;
	  ProductManager.getInventories( function(data){
			me.store.loadData(data);
	  });
	},
	init : function() {
        var me = this;
        this.store = new Ext.data.JsonStore({
			fields : ["product.id", "product.name", "totalQuantity", "totalQuantityForSale"]
		}),
		inventory_log_ds = new Ext.data.JsonStore({
		    fields : ["quantity", "type", "location.name", "createdTime", "comments"]
		});

        this.refresh();
		this.store.on('update', function(self, record){
			var updatedRec =  {id : record.get("product.id"), name : record.get("product.name"), 
			                   salePrice: record.get('product.salePrice')}; 	
			ProductManager.saveProduct(updatedRec, function(){			
			    me.refresh();
			});

		});
        
		var p_combo = new Ext.form.ComboBox({
	        store: this.store,
	        displayField: 'product.name',
	        valueField: 'product.id',
	        editable: false,
	        typeAhead: true,
	        mode: 'local',
	        triggerAction: 'all',
	        emptyText: '请选择',
	        selectOnFocus: true,
	        width: 100,
	        getListParent: function() {
	            return this.el.up('.x-menu');
	        },
	        iconCls: 'no-icon'
	    });


		
		var transform_menu = new Ext.menu.Menu({
	        style: {
	            overflow: 'visible'     // For the Combo popup
	        },
	        items: [ p_combo, {
                text: 'I like Ext',
                checked: true
            }, '-' ]
		});

        var other_in_menu = new Ext.menu.Menu({
	        style: {
	            overflow: 'visible'     // For the Combo popup
	        },
			items:[
			 {  xtype: 'combo', 
                 width:107,
			     store : location_ds,
    		     id: 'other-in-location',
		         forceSelection : true,
		         displayField: 'name',
		         valueField:'id',
				 editable:false,
				 typeAhead: true,
				 mode: 'local',
				 triggerAction: 'all',
				 selectOnFocus:true,
				 allowBlank: false,
				 value: location_ds.getCount()>0?location_ds.getAt(0).get('id'):'',
				 getListParent: function() {
				    return this.el.up('.x-menu');
				  }
			  },
			  {xtype: 'numberfield', id:'other-in-inventory',allowNegative: false, minValue:1, width:107},
			  {xtype: 'textarea', id : 'other-in-comments', height: 50},
			  {
                text: '提交', handler : function() { 
                	var reduce = Ext.getCmp('other-in-inventory');
                	if (reduce.isValid()){
                		var record = sm.getSelected(),
                		    pid = record.get('product.id'),
                		    comments = Ext.getCmp('other-in-comments').getValue(),
                		    location = Ext.getCmp('other-in-location').getValue(),
                		    amount = reduce.getValue();

                		ProductManager.saveInventoryChange(pid, 'other_in', location, amount, comments,function(data){
                		    me.refresh();
                		})
                	}               	
                } 
              }			
			]
		});
		
		var other_out_menu = new Ext.menu.Menu({
	        style: {
	            overflow: 'visible'     // For the Combo popup
	        },
			items:[
			  {  xtype: 'combo', 
                 width:107,
			     store : location_ds,
    		     id: 'other-out-location',
		         forceSelection : true,
		         displayField: 'name',
		         valueField:'id',
				 editable:false,
				 typeAhead: true,
				 mode: 'local',
				 triggerAction: 'all',
				 selectOnFocus:true,
				 allowBlank: false,
				 value: location_ds.getCount()>0?location_ds.getAt(0).get('id'):'',
				 getListParent: function() {
				    return this.el.up('.x-menu');
				  }
			  },
			  {xtype: 'numberfield', id:'other-reduce-inventory', allowNegative: false, minValue:1, width:107},
			  {xtype: 'textarea', id : 'other-out-comments', height: 50},
			  {
                text: '提交', handler : function() { 
                	var reduce = Ext.getCmp('other-reduce-inventory');
                	if (reduce.isValid()){
                		var record = sm.getSelected(),
                		    pid = record.get('product.id'),
                		    currentInventory = record.get('quantity'),
                		    comments = Ext.getCmp('other-out-comments').getValue(),
                		    location = Ext.getCmp('other-out-location').getValue();
                		    amount = reduce.getValue();
                		if (amount > currentInventory){
                			alert('不能大于当前库存量' + currentInventory + "!");
                			return;
                		}
                		ProductManager.saveInventoryChange(pid, 'other_out', location, -amount, comments,function(data){
                		    me.refresh();
                		})
                	}               	
                } 
              }			
			]
		});
		
        var tbar = 
		 [
           { id: 'product-add-btn', text:'新建', handler : function(){ 				
				var newRec = new Ext.data.Record({'product.name': '新产品', 'product.salePrice':0, quantity:0, quantityForSale: 0});
				editor.stopEditing();						
				me.store.insert(0, newRec);
				var grid = Ext.getCmp('product-grid');
				grid.getView().refresh();
				
				grid.getSelectionModel().selectRow(0);
				editor.startEditing(0);	 
		   } },'-',
		   
		   { id: 'product-other-in-btn', text:'其它入库', disabled: true, menu: other_in_menu},		 
		   { id: 'product-other-out-btn', text:'其它出库', disabled: true, menu:other_out_menu},
		   { id: 'location-management-btn', text:'仓库位置维护', handler: function(){
		        var  loc_ds = new Ext.data.JsonStore({
					fields: [ 'id', 'name' ]
				}),
				stock_ds = new Ext.data.JsonStore({
					fields: [ 'product.name', 'quantityForSale', 'quantity' ]
				}),
				loc_editor = new Ext.ux.grid.RowEditor({
					saveText: '保存',
					cancelText: '取消',
					clicksToEdit: 2
					
				});
				loc_ds.on('update', function(self, record){ 	
					ProductManager.saveLocation(record.get('id'),record.get('name'), function(){			
					    ProductManager.getAllLocation(function(data){ loc_ds.loadData(data); });
					});
		
				});
				
			    ProductManager.getAllLocation(function(data){ loc_ds.loadData(data); });
			    var loc_sm = new Ext.grid.RowSelectionModel({singleSelect:true});
		        loc_sm.on('selectionchange', function(sm){	
				    var rec = sm.getSelected();
				    
				    if (rec && rec.get('id') != null)
				    ProductManager.getStocksInLocation(rec.get('id'), function(data){
				        stock_ds.loadData(data);
				    });
				    else
				        stock_ds.removeAll();
				    
		        });
                var loc_win = new Ext.Window({
				    constrain : true,
					layout : 'border',
					width : 650,
					title: '仓库位置维护',
					closeAction : 'close',
					height : 590,
					resizable : false,
					shadow : true,
					modal : true,
					closable : true,
					border : false,										
					items:[
					{
						xtype:'grid',
						id : 'location-manage-grid',
						border: 1,
						layout:'fit',
						sm: loc_sm,
						region: 'west',
						width: 190,
						enableHdMenu: false,
						plugins: [loc_editor],
						store: loc_ds,
						columns: [
						   new Ext.grid.RowNumberer(),
						   {header: '名称', dataIndex : 'name', width: 130, editor: {
							xtype: 'textfield',
							allowBlank: false
						   } }					
						],
						tbar: [
				           { text:'新建', handler : function(){ 				
								var newRec = new Ext.data.Record({'name': '新位置'});
								loc_editor.stopEditing();						
								loc_ds.insert(0, newRec);
								var grid = Ext.getCmp('location-manage-grid');
								grid.getView().refresh();
								
								grid.getSelectionModel().selectRow(0);
								loc_editor.startEditing(0);	 
						   } },
						   {
						   	 text:'导出到Excel', handler: function(){
						   	 	ProductManager.inventories2excel(function(){ Ext.MessageBox.alert('信息', '导出至 D:\\lbc_data\\库存统计表.xls');})
						   	 }
						   },
						   { text: '关闭', handler: function() {
						   	    loc_win.close();
						   }}
						   ]		
					  },
					  {
					  	xtype: 'grid',
					  	store: stock_ds,				  	
					  	enableHdMenu: false,
					  	layout: 'fit',
					  	region: 'center',
					  	margins: '2 0 2 2',
					  	columns: [
						   new Ext.grid.RowNumberer(),
						   {header: '产品', dataIndex : 'product.name', width: 135},
						   {header: '可用数量', dataIndex : 'quantityForSale', width: 80},
						   {header: '最大数量', dataIndex : 'quantity', width: 80}						   
						]
					  }
			
					]
				 }).show();
		   	
		   }}
		  
	    ];
	    var editor = new Ext.ux.grid.RowEditor({
			saveText: '保存',
			cancelText: '取消',
			clicksToEdit: 2
			
		});
		
	    var sm = new Ext.grid.RowSelectionModel({singleSelect:true});
        sm.on('selectionchange', function(sm){	
		    var record = sm.getSelected();
		
		    Ext.getCmp('product-other-in-btn').setDisabled(!record);
		    Ext.getCmp('product-other-out-btn').setDisabled(!record);
		    
		    var days = Ext.getCmp('inventory-date-filter').getValue();
		    if (days == '') days = 30;
		    var sum_in = Ext.getCmp('sum-inventory-in'),
		        sum_out = Ext.getCmp('sum-inventory-out');
            if (record){
			    ProductManager.getInventoryHistories(record.get('product.id'), days, function(data){
			        inventory_log_ds.loadData(data);
			        var total_in=0, total_out=0, n;
			       
			        for (var i = 0; i<data.length;i++){
			        	n = data[i].quantity;
			        	
			        	if (n >=0)
			        	  total_in += n;
			        	else
			        	  total_out += n;
			        }
			        sum_in.setText(total_in);
			        sum_out.setText(-total_out);
			    });
			    
                ProductManager.getLocatedInventoriesByProductId(record.get('product.id'), function(data){
       	  	      p_stock_ds.removeAll();
       	  	      for (var i = 0; i < data.length; i++) {
       	  	      	p_stock_ds.insert(0,
       	  	      	 new Ext.data.Record({
       	  	      	    location:data[i].location.name,
       	  	      	    quantity:data[i].quantity,
       	  	      	    quantityForSale: data[i].quantityForSale
       	  	      	    })
       	  	      	  );       	  	      	
       	  	      }
       	  	 });
            } else {
		        inventory_log_ds.removeAll();
		        sum_in.setText('0');
		        sum_out.setText('0');
		        p_stock_ds.removeAll();
            }  
		    
        });
       var p_stock_ds = new Ext.data.SimpleStore({
			fields: [
			   'location',
			   'quantityForSale',
			   'quantity'
			]
		});
		this.tabpanel.add(
		  {	xtype:'panel',
		  	closable:true,
		  	id: 'product-info',
		  	title: '产品与库存',
		  	border: false,
			layout:'border',
			defaults: {
				split: true
			},
			items:[
			  {		
				xtype:'grid',
				store : me.store,
				sm: sm,
				id: 'product-grid',
				region: 'center',
				margins: '2 0 2 2',
                tbar: tbar,
				plugins: [editor],
				columns:[
					new Ext.grid.RowNumberer(),
					{  dataIndex: 'product.id', hidden: true },
					{
					   header: '名称',
					   dataIndex: 'product.name',
					   sortable: true,
					   width: 180,
					   editor: {
							xtype: 'textfield',
							allowBlank: false
						}

					},{
			            header: '库存',
			            dataIndex: 'totalQuantity',
			            width: 58
			            
			        },{
			        	header: '即用库存',
			        	dataIndex: 'totalQuantityForSale',
			        	width: 65,
			        	renderer: function(val){		        		
			        		if (val == null) return '';
					        if(val > 100){
					            return val;
					        }else{
					            return '<span style="color:red;">' + val + '</span>';
					        } 
			        	}
			        }
			        
					]			
	
          },
          {
		   xtype: 'tabpanel',
		   activeTab: 0,
		   width: 480,
		   region: 'east',
		   margins: '2 2 2 2',
           items:[{
              	xtype: 'grid',
              	title: '仓库分布信息',
              	store: p_stock_ds,
              	columns:[
					 {header: '仓库位置', dataIndex : 'location', width: 135},
					 {header: '可用数量', dataIndex : 'quantityForSale', width: 80},
					 {header: '最大数量', dataIndex : 'quantity', width: 80}
			    ]
           },		
           {
                xtype:'grid',							
				title:'库存变更记录',
				store : inventory_log_ds, 				
				tbar : 
				 ['日期范围(天): ', ' ',
                   new Ext.form.NumberField({                    
                     width:36,
                     value:'30',
                     allowNegative: false,
                     id:'inventory-date-filter'
                   }),'(0代表查看全部)','->','总入库:',new Ext.form.Label({id:'sum-inventory-in', text:'0'}), '-','总出库',new Ext.form.Label({id:'sum-inventory-out',text:'0'})],
                
				columns:[
					new Ext.grid.RowNumberer(),
					{header:'变更类型', width:65, dataIndex:'type', sortable: true,
					 renderer: function(val){
					        if(val == 'produce_in')
					            return '生产入库';
					        else if (val == 'sale_out')
					            return '销售出库';					      
					        else if (val == 'return_in')
					        	return '退货入库';
					        else if (val == 'transform_in')
					            return '改板入库';
					        else if (val == 'transform_out')
					            return '改板出库';
					        else if (val == 'other_in')
					            return '其它入库';
					        else if (val == 'other_out')
					            return '其它出库';
					        return '';    
			        	}					
					},
					{header:'数量', width: 42, dataIndex: 'quantity'},
					{xtype: 'datecolumn', format:'Y-m-d H:i', header:'日期', width: 100, dataIndex: 'createdTime', sortable: true},
					{header:'仓库', width:70, dataIndex: 'location.name'},
					{header:'备注',width:158, dataIndex: 'comments'}
					]
				
          }
          ]}]}
          
          ).show();

	}
});

